﻿namespace FiftyOne.Foundation.Mobile.Detection.Wurfl.Handlers
{
    using FiftyOne.Foundation.Mobile.Detection.Wurfl;
    using System;

    internal class SafariHandler : RegexSegmentHandler
    {
        private const string DEFAULT_DEVICE = "generic_xhtml";
        private static readonly string[] PATTERNS = new string[] { @"(?<=Mozilla/\d.\d \()[^)]+", @"(?<=AppleWebKit/)[\d.]+", @"(?<=Version/)[\d.]+", @"(?<=Safari/)[\d.]+" };
        private static readonly string[] UNSUPPORTED_ROOT_DEVICES = new string[] { "safari" };

        internal SafariHandler() : base(PATTERNS, new int[] { 3, 1, 1, 1 })
        {
            base._firstMatchOnly = true;
        }

        internal SafariHandler(string[] regexs, int[] weights) : base(regexs, weights)
        {
            base._firstMatchOnly = true;
        }

        protected internal override bool CanHandle(DeviceInfo device)
        {
            return (base.CanHandle(device) && this.CanHandleDevice(device));
        }

        protected internal override bool CanHandle(string userAgent)
        {
            return (((userAgent.StartsWith("Mozilla") && userAgent.Contains("Safari")) && (!userAgent.Contains("iPhone") && !userAgent.Contains("iPod"))) && !userAgent.Contains("iPad"));
        }

        private bool CanHandleDevice(DeviceInfo device)
        {
            foreach (string str in UNSUPPORTED_ROOT_DEVICES)
            {
                if (str == device.DeviceId)
                {
                    return false;
                }
            }
            if (device.FallbackDevice != null)
            {
                return this.CanHandleDevice(device.FallbackDevice);
            }
            return true;
        }
    }
}

